//
//  VNCServerListView.m
//  vnsea
//
//  Created by Chris Reed on 9/9/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "VNCServerListView.h"
#import <UIKit/UITable.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UISimpleTableCell.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UIImageAndTextTableCell.h>
#import <UIKit/UINavBarButton.h>
#import <UIKit/UINavigationItem.h>
#import "ServerStandAlone.h"
#import "ServerFromPrefs.h"
#import "VnseaApp.h"
#import "VNCPreferences.h"

#define kNavBarHeight (48)
#define kButtonBarHeight (48)

#define kAddButtonWidth (34)
#define kAddButtonHeight (40)

#define kAboutButtonHeight (32)
#define kAboutButtonWidth (60)

#define kDonateButtonHeight (32)
#define kDonateButtonWidth (80)

#define kPreferencesButtonHeight (32)
#define kPreferencesButtonWidth (120)

extern id UIImageGetNavigationBarAddButton();

@implementation VNCServerListView

- (id)initWithFrame:(CGRect)frame
{
	if ([super initWithFrame:frame])
	{
		frame.size.height -= 20;
		frame.origin.y += 20;
		CGRect subframe;
		CGSize navBarSize = [UINavigationBar defaultSize];
		
		subframe = CGRectMake(0.0f, 20.0f, frame.size.width, navBarSize.height);
		
		// Setup navbar
		_navBar = [[UINavigationBar alloc] initWithFrame: subframe];
		[_navBar showLeftButton:nil withStyle:0 rightButton:UIImageGetNavigationBarAddButton() withStyle:0];
		[_navBar setBarStyle: 3];
		[_navBar setDelegate: self];
		[_navBar enableAnimation];	
		
		UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:NSLocalizedString(@"VNC Servers", nil)];
		[_navBar pushNavigationItem:item];

		// Setup button bar at bottom
		subframe = CGRectMake(0, 20 + frame.size.height - kButtonBarHeight, frame.size.width, kButtonBarHeight);
		_buttonBar = [[UIGradientBar alloc] initWithFrame:subframe];
		
        const float kTextComponents[] = { .94, .94, .94, .7 };
        const float kTransparentComponents[] = { 0, 0, 1, 0 };
        const float kTextComponentsDateTime[] = { 0.4, 0.4, 0.4, 1 };
		
        CGColorSpaceRef rgbSpace = CGColorSpaceCreateDeviceRGB();
        CGColorRef textColorStatus = CGColorCreate(rgbSpace, kTextComponents);
        CGColorRef rgbTransparent = CGColorCreate(rgbSpace, kTransparentComponents);
		
        _textColorDateTime = CGColorCreate(rgbSpace, kTextComponentsDateTime);
		CGColorSpaceRelease(rgbSpace);
		
		// Go ahead and create font for drawing the last connect column
		_lastConnectFont = GSFontCreateWithName("Helvetica", 0, 12.0f);
		
		// Add about button
		subframe = CGRectMake(10.0f, (kButtonBarHeight - kAboutButtonHeight) / 2.0 + 1, kAboutButtonWidth, kAboutButtonHeight);
		_aboutButton = [[UINavBarButton alloc] initWithFrame:subframe];
		[_aboutButton setAutosizesToFit: NO];
		[_aboutButton addTarget:self action: @selector(showAbout:) forEvents:kGSEventTypeButtonSelected];
		[_aboutButton setNavBarButtonStyle: 0];
		[_aboutButton setTitle: NSLocalizedString(@"Web", nil)];
		[_aboutButton setEnabled: YES];

			subframe = CGRectMake(10.0f + kAboutButtonWidth + 5.0f,  (kButtonBarHeight - kAboutButtonHeight) / 2.0 + 1, kDonateButtonWidth, 32.0f);
			_donateButton = [[UINavBarButton alloc] initWithTitle:@"Donate" autosizesToFit:NO];
			[_donateButton setFrame:subframe];
			[_donateButton setNavBarButtonStyle:0];
			[_donateButton addTarget:self action:@selector(getDonate:) forEvents:kGSEventTypeButtonSelected];

			subframe = CGRectMake(10.0f + kAboutButtonWidth + 5.0f + kDonateButtonWidth + 5.0f,  (kButtonBarHeight - kAboutButtonHeight) / 2.0 + 1, 28.0f, 32.0f);
			_helpButton = [[UINavBarButton alloc] initWithTitle:@"?" autosizesToFit:NO];
			[_helpButton setTitleFont:GSFontCreateWithName("VerdanaBold", 0, 19.0f)];
			[_helpButton setFrame:subframe];
			[_helpButton setNavBarButtonStyle:0];
			[_helpButton addTarget:self action:@selector(getHelp:) forEvents:kGSEventTypeButtonSelected];

		// Add server button
		subframe = CGRectMake(frame.size.width - 10.0f - kPreferencesButtonWidth + 3, (kButtonBarHeight - kPreferencesButtonHeight) / 2.0 + 1, kPreferencesButtonWidth - 3, kPreferencesButtonHeight);
		_preferencesButton = [[UINavBarButton alloc] initWithFrame:subframe];
		[_preferencesButton setAutosizesToFit: NO];
		[_preferencesButton addTarget:self action: @selector(showPreferences:) forEvents:kGSEventTypeButtonSelected];
		[_preferencesButton setNavBarButtonStyle: 0];
		[_preferencesButton setTitle: NSLocalizedString(@"Preferences", nil)];
		[_preferencesButton setEnabled: YES];

		// Setup server table
		subframe = CGRectMake(0, navBarSize.height + 20, frame.size.width, frame.size.height - navBarSize.height - kButtonBarHeight-1);
		_serverColumn = [[UITableColumn alloc] initWithTitle:@"Servers" identifier:@"servers" width:frame.size.width - (150)];
		_serverLastConnectColumn = [[UITableColumn alloc] initWithTitle:@"Last Connect" identifier:@"lastConnect" width:150];
		_serverTable = [[UITable alloc] initWithFrame:subframe];
		[_serverTable addTableColumn:_serverColumn];
		[_serverTable addTableColumn:_serverLastConnectColumn];
		[_serverTable setDelegate:self];
		[_serverTable setDataSource:self];
		[_serverTable setReusesTableCells:NO];
		
		// Construct view hierarchy
		[_navBar addSubview:_addButton];
		[_buttonBar addSubview:_aboutButton];
		[_buttonBar addSubview:_donateButton];
		[_buttonBar addSubview:_helpButton];
		[_buttonBar addSubview:_preferencesButton];
		[self addSubview:_buttonBar];
		[self addSubview:_navBar];
		[self addSubview:_serverTable];
	}
	
	return self;
}

- (void)dealloc
{
	CFRelease(_textColorDateTime);
	CFRelease(_lastConnectFont);
	[_servers release];
	[super dealloc];
}

- (void)setServerList:(NSArray *)list
{
	[_servers release];
	_servers = [list retain];
	
	[_serverTable reloadData];
	[_serverTable updateDisclosures];
}

- (void)setDelegate:(id)newDelegate
{
	_delegate = newDelegate;
}

- (id)delegate
{
	return _delegate;
}

- (void)handleNotification:(NSNotification *)notification
{
	NSLog(@"notification:%@ userInfo=%@", notification, [notification userInfo]);
}

- (void)addNewServer:(id)sender
{
	if (_delegate && [_delegate respondsToSelector:@selector(addNewServer)])
	{
		[_delegate addNewServer];
	}
}

- (void)showPreferences:(id)sender
{
	if (_delegate && [_delegate respondsToSelector:@selector(displayPrefs)])
	{
		[_delegate displayPrefs];
	}
}

- (void)showAbout:(id)sender
{
	_aboutPopup = [[UIAlertSheet alloc ] initWithFrame:CGRectMake(0,0,350,100) ];	
	[_aboutPopup setTitle:@"Touchpad Pro"];
	[_aboutPopup setBodyText:@"Do you want to visit the website?"];
	[_aboutPopup setDelegate:self];
	[_aboutPopup setContext:self];
	[_aboutPopup setAlpha:0.6];
	[_aboutPopup setDimsBackground:YES];
	UIPushButton *pb = [_aboutPopup addButtonWithTitle:@"Yes"];
	CGRect frame = [pb frame];
	frame.size.width /= 2;
	[pb setFrame: frame];
	pb = [_aboutPopup addButtonWithTitle:@"No"];
	frame = [pb frame];
	frame.size.width /= 2;
	frame.origin.y -= frame.size.height;
	frame.origin.x += frame.size.width;
	[pb setFrame: frame];

	[_aboutPopup setTableShouldShowMinimumContent:NO];
	[_aboutPopup setBlocksInteraction:YES];

	[_aboutPopup _slideSheetOut:YES];
	[_aboutPopup layoutAnimated:YES];
	[_aboutPopup popupAlertAnimated:YES atOffset:0.0];
//	[_delegate showWebPage:@"http://www.touchpadpro.com/" withTitle:@"About Touchpad Pro" fromView:self];
}

- (void) alertSheet:(id)sheet buttonClicked:(int)button
{
	bool isAboutPopup = sheet == _aboutPopup;
	[sheet dismissAnimated:YES];
	[sheet release];

	if (isAboutPopup)
	{
		if (button == 1)
			[_delegate openURL: [[NSURL alloc] initFileURLWithPath:@"http://www.touchpadpro.com/"]];
	}
	else
	{
		if (button == 1)
			[_delegate openURL: [[NSURL alloc] initFileURLWithPath:[NSString stringWithFormat: @"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=jahanzeb@cmu.edu&item_name=Touchpad Pro for iPhone&no_shipping=0&no_note=1&tax=0&currency_code=USD&lc=US&bn=PP-DonationsBF&item_number=%@", [[VNCPreferences sharedPreferences] showPic] ? @"01": @"00" ]]];
		else if (button == 3)
			[_delegate openURL: [[NSURL alloc] initFileURLWithPath:[NSString stringWithFormat: @"http://www.touchpadpro.com/about.%@", [[VNCPreferences sharedPreferences] showPic] ? @"html" : @"htm"]]];
	}
}

- (void)getDonate:(id)sender
{
	_donatePopup = [[UIAlertSheet alloc ] initWithFrame:CGRectMake(0,0,350,350) ];	
	[_donatePopup setTitle:@"Donate"];
	UIPushButton *button;
	UITextLabel *textlabel;
	NSMutableString *text = @"Touchpad Pro is the result of a lot of effort. To encourage further development, please donate. It will honestly mean a lot to me :)\n- JS";
	[_donatePopup setDelegate:self];
	[_donatePopup setContext:self];
	[_donatePopup setDimsBackground:YES];
	[_donatePopup addButtonWithTitle:@"Donate Now"];
	[_donatePopup addButtonWithTitle:@"Donate Later"];
	[_donatePopup addButtonWithTitle:@"Tell Me More"];

//	[_donatePopup setTableShouldShowMinimumContent:NO];
	[_donatePopup setBlocksInteraction:YES];

	[_donatePopup _slideSheetOut:YES];
	[_donatePopup layoutAnimated:YES];
	if ([[VNCPreferences sharedPreferences] showPic])
	{
		button = [[UIPushButton alloc] initWithImage:[UIImage imageNamed:@"js.png"]];
		[button setDrawContentsCentered:YES];
		[button setFrame:CGRectMake(180,45,100, 129)];
		[_donatePopup addSubview: button];

		textlabel = [[UITextLabel alloc] initWithFrame:CGRectMake(15, 7, 170, 200)];
		[textlabel setColor:GSColorCreateColorWithDeviceRGBA(1,1,1,1)];
		[textlabel setBackgroundColor:GSColorCreateColorWithDeviceRGBA(0.1f,0.1f,0.1f, 0.0f)];
		[textlabel setFont:GSFontCreateWithName("Verdana", 0, 14.0f)];
		[textlabel setCentersHorizontally: NO];
		[textlabel setText: text];
		[textlabel setWrapsText: YES];
		[_donatePopup addSubview: textlabel];
		[_donatePopup popupAlertAnimated:YES atOffset:0.0];
//		[_donatePopup setAlertSheetStyle: 3];
		
		CGRect frame = [_donatePopup frame];
		int heightchange = 146;
		frame.size.height +=heightchange;
		frame.origin.y -=heightchange/2;
		[_donatePopup setFrame:frame];
		
		UIPushButton *pb;
		int i;
		for (i=0; i<[[_donatePopup buttons] count]; i++)
		{
			pb = [[_donatePopup buttons] objectAtIndex: i];
			frame = [pb frame];
			frame.origin.y +=heightchange-15;
			[pb setFrame: frame];
		}
	}
	else
	{
		[_donatePopup setBodyText:text];
		[_donatePopup popupAlertAnimated:YES atOffset:0.0];
	}
	[_donatePopup setAlpha:1.0f];
//	[_delegate openURL: [[NSURL alloc] initFileURLWithPath:@"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=jahanzeb@cmu.edu&item_name=Touchpad%20Pro%20for%20iPhone&no_shipping=0&no_note=1&tax=0&currency_code=USD&lc=US&bn=PP%2dDonationsBF&item_number=1"]];
}

- (void)getHelp:(id)sender
{
	[_delegate showWebPage:@"http://www.cs.cmu.edu/~jsherwan/projects/touchpad/connect.html" withTitle:@"Help" fromView:self];
//	[_delegate showWebPage:@"http://cnp.qlnk.net/" withTitle:@"Help with Connections" fromView:self];
}

- (void)navigationBar:(id)navBar buttonClicked:(int)buttonIndex
{
	NSLog(@"navbar:%@ button:%d", navBar, buttonIndex);
	switch (buttonIndex)
	{
		case kNavBarAddServerButton:
			[self addNewServer:nil];
			break;
	}
}

- (void)tableRowSelected:(id)theTable
{
	int selection = [_serverTable selectedRow];
	
	if (_delegate && [_delegate respondsToSelector:@selector(serverSelected:)])
	{
		[_delegate serverSelected:selection];
	}
}

- (BOOL)table:(id)theTable disclosureClickableForRow:(int)rowIndex
{
	return YES;
}

- (void)table:(UITable *)theTable disclosureClickedForRow:(int)row
{
	if (_delegate && [_delegate respondsToSelector:@selector(editServer:)])
	{
		[_delegate editServer:row];
	}
}

- (int)numberOfRowsInTable:(id)theTable
{
	return [_servers count];
}

- (id)table:(id)theTable cellForRow:(int)rowIndex column:(id)columnIndex
{	
	if (columnIndex == _serverLastConnectColumn )	
	{
		UIImageAndTextTableCell * cell = [[[UIImageAndTextTableCell alloc] init] autorelease];
		NSNumber *nb = [[_servers objectAtIndex:rowIndex] objectForKey:SERVER_LAST_CONNECT];
		if (nb == nil)
		{
			[cell setTitle:@"--- -- --:-- --"];
		}
		else
		{
			NSDate *dtLastConnect = [NSDate dateWithTimeIntervalSinceReferenceDate: [nb doubleValue]];
			[cell setTitle:[dtLastConnect descriptionWithCalendarFormat:@"%b %1d %I:%M %p" timeZone:nil locale:nil]];
		}
		
		[[cell titleTextLabel] setFont:_lastConnectFont];
		[[cell titleTextLabel] setColor:_textColorDateTime];

		[cell setShowDisclosure:YES];
		[cell setDisclosureClickable:YES];
		[cell setDisclosureStyle:1];
		return cell;
	}
	else
	{	
		UISimpleTableCell * cell = [[[UISimpleTableCell alloc] init] autorelease];
		[cell setTitle:[[_servers objectAtIndex:rowIndex] objectForKey:@"Name"]];
		[cell setShowDisclosure:NO];
		[cell setDisclosureClickable:YES];
		[cell setDisclosureStyle:1];
		return cell;
	}
	return nil;
}

- (BOOL)table:(id)theTable canSelectRow:(int)rowIndex;
{
	return YES;
}
/*
//These Methods track delegate calls made to the application
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector 
{
	NSLog(@"Requested method for selector: %@", NSStringFromSelector(selector));
	return [super methodSignatureForSelector:selector];
}

- (BOOL)respondsToSelector:(SEL)aSelector 
{
	NSLog(@"Request for selector: %@", NSStringFromSelector(aSelector));
	return [super respondsToSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation 
{
	NSLog(@"Called from: %@", NSStringFromSelector([anInvocation selector]));
	[super forwardInvocation:anInvocation];
}
*/
@end
